package com.cdm.forum.interceptor;

import com.cdm.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${forum.login.url}")
    private String defaultUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            //证明登陆过
            return true;
        }
        //校验不通过，跳转登录页面
        //1.response.sendRedirect("/sign-in.html"); //这种方式不好改界面名字就要全部改

        //2.yml里面定义属性,校验url
        if(!defaultUrl.startsWith("/")) {
            defaultUrl = "/" + defaultUrl;
        }

        response.sendRedirect(defaultUrl);
        //中断流程
        return false;
    }

}
